<template>
  <BaseVxeGrid ref="vxeGridRef" :gridOptions="gridOptions">
    <template #header>
      <ElForm label-width="100" label-position="left" style="margin-top: 10px;">
        <ElRow>
          <ElCol :span="24">
            <ElFormItem label="组件配置">
              <ElInput></ElInput>
            </ElFormItem>
          </ElCol>

          <ElCol :span="24">
            <ElDivider content-position="left">列显示设置</ElDivider>
          </ElCol>
          <template v-for="(item, index) in tableConfig.visible" :key="index">
            <ElCol :span="4">
              <ElFormItem :label="item.title">
                <ElSwitch v-model="item.visible"></ElSwitch>
              </ElFormItem>
            </ElCol>
          </template>

          <ElCol :span="24">
            <ElDivider content-position="left">列样式设置</ElDivider>
          </ElCol>
          <ElCol :span="24">
            <ElFormItem label="列样式设置">
              <CusConstraints :cell-styles="tableConfig.cellStyles" />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>
    </template>
  </BaseVxeGrid>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import type { VxeGridProps } from 'vxe-table'
import BaseVxeGrid from '../components/BaseVxeGrid.vue'
import type { ComponentExposed } from 'vue-component-type-helpers'
import CusConstraints from './components/cusConstraints.vue'

interface RowVO {
  storage: string
  drug_code: string
  drug_spec: string
  drug_id: string
  spec_alias: string
  drug_name: string
  trade_name: string
  factory: string
  factory_alias: string
  drug_units: string
  dose_per_unit: number
  dose_units: string
  drug_form: string
  retail_price: number
  input_code: string
  pack_first_day: boolean
  dispensing_property: string
}

const tableConfig = ref({
  visible: [
    {
      field: 'retail_price',
      title: "零售价",
      visible: false,
    }, {
      field: 'drug_name',
      title: "药品名称",
      visible: true,
    }, {
      title: "贴签机",
      field: 'tagMachine',
      visible: false,
    }
  ],
  cellStyles: [
    {
      colField: 'drug_state',
      constraints: [
        {
          conditionName: '细胞毒',
          condition: '==',
          conditionVal: '细胞毒',
          style: { backgroundColor: '#D4FF00', color: '#006AFF', fontStyle: 'italic', fontSize: '14px', fontWeight: 'bolder' },
        },
        {
          conditionName: '缺货药品',
          condition: '==',
          conditionVal: '缺货',
          style: { backgroundColor: '#FF4400', color: 'white', fontStyle: 'italic', fontSize: '14px', fontWeight: 'bolder' },
        },
        {
          conditionName: '异常药品',
          condition: '==',
          conditionVal: '异常',
          style: { backgroundColor: '#008CFF', color: '#FF00EA', fontStyle: 'italic', fontSize: '14px', fontWeight: 'bolder' },
        },
      ],
    },
  ]
})

// https://vxetable.cn/#/component/grid/checkbox/range 滑动复选框多选
const gridOptions = ref<VxeGridProps<RowVO>>({
  cellStyle({ row, column }) {
    let funcStrs = "";
    const value = row[column.field as keyof RowVO];

    for (const item of tableConfig.value.cellStyles) {
      if (column.field == item.colField)
        for (const style of item.constraints) {
          const funcStr = `if('${value}' ${style.condition} '${style.conditionVal}') return ${JSON.stringify(style.style)};`;
          funcStrs += funcStr;
          // console.log(`output->`, new Function(funcStr)());
          // console.log(`output->funcStr`, funcStr)
        }
    }
    return new Function(funcStrs)();

    // if (column.field === 'drug_name') {
    //   return <VxeComponentStyleType>{ backgroundColor: '#ff0000', color: 'white', fontStyle: 'italic', fontSize: '14px', fontWeight: 'bolder' }
    // }
  },
  columns: [
    { type: 'checkbox', fixed: 'left' },
    { minWidth: '100px', title: '序号', type: 'seq', fixed: 'left' },
    { minWidth: '100px', field: 'drug_name', title: '药品名称', fixed: 'left', sortable: true },
    { minWidth: '100px', field: 'drug_spec', title: '药品规格', fixed: 'left' },
    { minWidth: '100px', field: 'factory', title: '生产厂商', fixed: 'left' },
    { minWidth: '100px', field: 'drug_state', title: '药品状态' },
    { minWidth: '100px', field: 'storage', title: '库存位置' },
    { minWidth: '100px', field: 'drug_code', title: '药品编码' },
    { minWidth: '100px', field: 'pack_first_day', title: '首日打包', },
    { minWidth: '100px', field: 'dispensing_property', title: '摆药类型' },
    { minWidth: '100px', field: 'spec_alias', title: '规格别名' },
    { minWidth: '100px', field: 'factory_alias', title: '厂商别名' },
    { minWidth: '100px', field: 'drug_units', title: '单位' },
    { minWidth: '100px', field: 'dose_per_unit', title: '单位剂量' },
    { minWidth: '100px', field: 'tagMachine', title: '贴签机' },
  ],
  data: [],
})

// 检查 column 的 visible 是否显示
gridOptions.value.columns?.forEach(col => {
  for (const item of tableConfig.value.visible) {
    if (col.field == item.field)
      col.visible = item.visible;
  }
})


const vxeGridRef = ref<ComponentExposed<typeof BaseVxeGrid<RowVO>>>();
watch(tableConfig.value.visible, (newVal) => {
  const $grid = vxeGridRef.value?.getVxeGridRef();

  for (const item of newVal) {
    const col = $grid!.getColumnByField(item.field);
    if (col)
      col.visible = item.visible;
  }
  $grid?.refreshColumn()
}, { deep: true })

function queryInit() {
  // 从接口获取数据
  fetch('https://mock.presstime.cn/mock/66f26d8d0b20e0d6a1d5a491/test/getDrugList', {
    headers: {
      'content-type': 'application/json',
    },
    method: 'GET',
  })
    .then((res) => res.json())
    .then((res) => {
      const tmpData = [...res.result.items].slice(0, 3)
      gridOptions.value.data = tmpData
    })
}
queryInit()
</script>

<style scoped></style>
